import mysql.connector
from mysql.connector import Error
from .db_config import DB_CONFIG

class DatabaseHandler:
    def __init__(self):
        self.connection = None
        self.cursor = None
        
    def connect(self):
        """建立数据库连接"""
        try:
            self.connection = mysql.connector.connect(**DB_CONFIG)
            self.cursor = self.connection.cursor(dictionary=True)
            return True
        except Error as e:
            print(f"数据库连接错误: {e}")
            return False
            
    def disconnect(self):
        """关闭数据库连接"""
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()
            
    def execute_query(self, query, params=None):
        """执行查询操作"""
        try:
            self.cursor.execute(query, params or ())
            return self.cursor.fetchall()
        except Error as e:
            print(f"查询执行错误: {e}")
            return None
            
    def execute_update(self, query, params=None):
        """执行更新操作"""
        try:
            self.cursor.execute(query, params or ())
            self.connection.commit()
            return True
        except Error as e:
            print(f"更新执行错误: {e}")
            self.connection.rollback()
            return False
            
    def verify_login(self, username, password):
        """验证用户登录"""
        query = """
            SELECT * FROM users
            WHERE username = %s AND password = %s
        """
        if self.connect():
            try:
                result = self.execute_query(query, (username, password))
                return result[0] if result else None
            finally:
                self.disconnect()
        return None 